var express = require('express');
var router = express.Router();
var {userModel} = require('../database/model/clientModel')
var bcrypt = require('bcryptjs')
var salt = bcrypt.genSaltSync(10); //加密盐
var jwt = require('jsonwebtoken')
var secret = 'asdfasdfasdf546546asdfasdfa2131asdfaf' //私钥


//注册
router.post('/',(req,res)=>{
  console.log(req.body);
  let {pass,username} = req.body
  userModel.find({username}).then(result=>{
    console.log(result);
    if(result.length){ //已被占用
      res.send({
        code:0,
        msg:'账号已被占用'
      })
      return
    }
    var hash = bcrypt.hashSync(pass, salt); //密码加密
    new userModel({
      username,
      pass:hash
    }).save().then(result=>{
      res.send({
        code:1,
        msg:'注册成功'
      })
    })
  })
})

// 登录
router.get('/', function(req, res, next) {
  let {username,pass} = req.query
  userModel.find({username}).then(result=>{
    if(!result.length){ //判断账号是否存在
      res.send({
        code:0,
        msg:'账号不存在，请先注册'
      })
      return
    }
    let bool = bcrypt.compareSync(pass,result[0].pass) //密码比对
    if(!bool){
      res.send({
        code:0,
        msg:'密码错误,请重试'
      })
      return
    }
    let userInfo = result[0]
    userInfo.pass = ''
    jwt.sign({  //签发token
      time:Date.now(), //签发时间
      limit:30*1000  //有效时长
    },
    secret, //私钥，未来可以用于解析token
    (err,token)=>{ 
      // console.log(token);
      res.send({
        code:1,
        msg:'登录成功',
        data:{
          userInfo,
          token
        }
      })
    })
  })
});

module.exports = router;
